package com.google.android.location.content;




import com.google.android.location.content.libservices.IRouteRecordingService;
import com.google.android.location.content.libcontent.RoutesColumns;
import com.google.android.location.content.libdata.MyRouteProvider;
import com.google.android.location.content.liblogs.MyLogClass;
import com.google.android.location.content.menus.MenuManager;
import com.google.android.location.content.menus.NavigationControls;
import com.google.android.location.content.mymaps.MyMapActivity;
import com.google.android.location.content.mymaps.MyMapPredictionActivity;
import com.google.android.location.content.route.RouteManager;
import com.google.android.location.content.route.RouteMapDataListener;
import com.google.android.location.content.service.ConnectionServiceManager;
import com.google.android.location.content.service.ServiceControl;
import com.google.android.location.content.service.ServiceManager;
import com.google.android.location.content.utilities.UriProfiler;
import com.google.android.location.predict.RoutesPredictActivity;
import com.google.android.maps.MapActivity;
import com.google.android.locatiom.maps.myroutes.R;




import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.IBinder.DeathRecipient;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.Toast;

import static com.google.android.location.content.Constants.*;



public class StartMenu extends TabActivity implements OnTouchListener {
	private static final int DIALOG_EULA_ID = 0;
	MyRouteProvider myRouteProvider;
	SharedPreferences preferences;
	MenuManager menuManager;
	SharedPreferences sharedPreference;
	boolean startNewRequested;
	NavigationControls navigationControls;

	IRouteRecordingService connectionService;
	private boolean startNewRecording = false;
	/**
	 * route manager of the current route
	 */
	RouteManager dataHub;
	ConnectionServiceManager serviceConnectionManager;
	private final Runnable changeTab = new Runnable() {
		public void run() {
			getTabHost().setCurrentTab(navigationControls.getCurrentIcons());
		}
	};
	private Runnable establishConnection = new Runnable() {
		@Override
		public void run() {
			synchronized (serviceConnectionManager) {
				IRouteRecordingService iService = serviceConnectionManager
						.getServiceIfBound();
				if (startNewRecording && iService != null) {
					Log.i(MyLogClass.TAG, "Start New TrackRequested");
					startNewRecording = false;
					startNewRouteRecording(iService);
				} else if (!startNewRecording) 
				{
					Log.d(MyLogClass.TAG, "Not yet recording...");
				}
			}
		}
	};

	private void startNewRouteRecording(IRouteRecordingService iService) {
		Log.i(MyLogClass.TAG, "Recording service...");
		try 
	    {
	      long recordingRouteId = iService.startNewRouteId();
	      // Select the recording track.
	      dataHub.loadRoute(recordingRouteId);
	      Toast.makeText(this, getString(R.string.route_record_success), Toast.LENGTH_SHORT).show();
	      // TODO: We catch Exception, because after eliminating the service process
	      // all exceptions it may throw are no longer wrapped in a RemoteException.
	    } catch (Exception e) 
	    {
	      Toast.makeText(this, getString(R.string.route_record_error), Toast.LENGTH_SHORT).show();
	      Log.w(TAG, "Unable to start recording.", e);
	    }
	  }
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final Resources res = getResources();
		dataHub = ((MyRouteAppManager)getApplication()).getRouteDataHub();
		final TabHost tabHost = getTabHost();
		tabHost.addTab(tabHost
				.newTabSpec("tab1")
				.setIndicator("Map",
						res.getDrawable(android.R.drawable.ic_menu_mapmode))
				.setContent(new Intent(this, MyMapActivity.class)));
		tabHost.addTab(tabHost
				.newTabSpec("tab2")
				.setIndicator("Map Predictions",
						res.getDrawable(android.R.drawable.ic_menu_mapmode))
				.setContent(new Intent(this, MyMapPredictionActivity.class)));
		tabHost.addTab(tabHost
				.newTabSpec("tab3")
				.setIndicator("Route Stats",
						res.getDrawable(R.drawable.menu_statistics))
				.setContent(new Intent(this, StatsActivity.class)));

		serviceConnectionManager = new ConnectionServiceManager(this, establishConnection);
		myRouteProvider = MyRouteProvider.Factory.getRouteProvider(this);
		tabHost.getTabWidget().setVisibility(View.GONE);
		preferences = getSharedPreferences(Constants.SETTINGS_NAME,
				Context.MODE_PRIVATE);
		RelativeLayout layout = new RelativeLayout(this);
		LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		layout.setLayoutParams(params);
		navigationControls = new NavigationControls(this, layout,
				getResources().obtainTypedArray(R.array.left_icons),
				getResources().obtainTypedArray(R.array.right_icons), changeTab);
		navigationControls.show();
		tabHost.addView(layout);
		menuManager = new MenuManager(this);
		layout.setOnTouchListener(this);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			navigationControls.show();
		}
		return false;
	}

	/**
	 * create the contextmenu
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		return menuManager.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menuManager.onPrepareOptionsMenu(menu,
				myRouteProvider.getLastRoute() != null, ServiceControl.isRecording(this,
								serviceConnectionManager.getServiceIfBound(),
								preferences), true);
		return super.onPrepareOptionsMenu(menu);
	}



	/**
	 * check the current status of the app and the service if it's recording
	 * already then start and bind the service
	 */
	@Override
	protected void onStart() {
		super.onStart();
		dataHub.startTracking();
		Log.i(MyLogClass.TAG, "StartActivity.dataHub:Load tracking manager");
		if (ServiceControl.isRecording(getApplicationContext(), null,
				preferences)) {
			serviceConnectionManager.startAndBindService();
		}
		Intent intent = getIntent();
	    String action = intent.getAction();
	    Uri data = intent.getData();
	    if ((Intent.ACTION_VIEW.equals(action) || Intent.ACTION_EDIT.equals(action)) 
	        && RoutesColumns.CONTENT_ITEMTYPE.equals(intent.getType())
	        && UriProfiler.matchesContentUri(data, RoutesColumns.CONTENT_URI)) 
	    {
	      long routeId = ContentUris.parseId(data);
	      dataHub.loadRoute(routeId);
	    }
	}
    @Override
    protected void onStop() {
     	super.onStop();
     	dataHub.stopListening();

    }
	@Override
	protected void onPause() {
		Log.i(MyLogClass.TAG, "StartActivity : OnPause");
		super.onPause();
	}

	@Override
	protected void onResume() {
		Log.d(MyLogClass.TAG, "StartActivity : OnResume");
		serviceConnectionManager.bindServiceIfRunning();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		Log.d(MyLogClass.TAG, "StartActivity :  OnDestroy");
		serviceConnectionManager.unBindService();
		super.onDestroy();
	}





	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return menuManager.onOptionsItemSelected(item) ? true : super
				.onOptionsItemSelected(item);
	}
	/**
	   * Stops the track recording service and unbinds from it. Will display a toast
	   * "Stopped recording" and pop up the Track Details activity.
	   */
	public void stopRecording() {
		 // Save the track id as the shared preference will overwrite the recording track id.
	    SharedPreferences sharedPreferences = getSharedPreferences(
	        Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
	    long currentRouteId = sharedPreferences.getLong(getString(R.string.recording_route_key), -1);

	    IRouteRecordingService routeRecordingService = serviceConnectionManager.getServiceIfBound();
	    if (routeRecordingService != null) {
	      try {
	        routeRecordingService.endCurrentRoute();
	      } catch (Exception e) {
	        Log.e(TAG, "Unable to stop recording.", e);
	      }
	    }

	    serviceConnectionManager.stop();

	    if (currentRouteId > 0) {
	      Intent intent = new Intent(StartMenu.this, RouteDetails.class);
	      intent.putExtra("routeid", currentRouteId);
	      intent.putExtra("hasCancelButton", false);
	      startActivity(intent);
	    }

	}

	public void startRecording() {
		synchronized (serviceConnectionManager) 
		{
			startNewRecording = true;
			serviceConnectionManager.startAndBindService();
			establishConnection.run();
		}
	}

	
}